#include "password.h"

static int getSalt(char* salt, const char* password){
    int count = 0;
    int i;
    for(i = 0; count<3 && password[i]; i++){
        if(password[i]=='$'){
            count++;
        }
    }
    strncpy(salt,password,i-1);
}

int passswordAuth(const userinfo_t* puserinfo){
    char username[32]={0};
    char clearPasswd[32]={0};
    char salt[512]={0};
    strcpy(username,puserinfo->username);
    strcpy(clearPasswd,puserinfo->password);
    //printf("name = %s\n",username);
    struct spwd* sp;
    sp = getspnam(username);
    //printf("saltpasswd = %s\n",sp->sp_pwdp);
    if(sp  == NULL){
      //  printf("user does not exist!\n");
        return 1;
    }
    getSalt(salt,sp->sp_pwdp); 
    //printf("salt = %s\n",salt);
    if(strcmp(sp->sp_pwdp,crypt(clearPasswd,salt)) == 0){
        return 0;
    }
    else{
        return 2;
    }
}
